package zheezes.util;

/**
 * @author hcconquer@gmail.com
 */
public class ZByte {
	/**
	 * get the bit value
	 * 
	 * @param b
	 *         byte value
	 * @param o
	 *         offset, 0 1 2 3 4 5 6 7
	 * @return bit value
	 */
	public static int bitget(int b, int o) {
		if (o < 0 || o > 7) {
			return -1;
		}
		b = b >> (7 - o);
		b = b & 0x01;
		return b;
	}
	
	/**
	 * set the bit value
	 * 
	 * @param b
	 *         byte value
	 * @param o
	 *         offset, 0 1 2 3 4 5 6 7
	 * @return the byte after set
	 */
	public static int bitset(int b, int o, int v) {
		if (o < 0 || o > 7) {
			return -1;
		}
		if (v == 0) {
			b = b & ~(0x01 << (7 - o));
		} else {
			b = b | (0x01 << (7 - o));
		}
		return b;
	}
	
	/**
	 * byte 0x81 --> 129 not -127
	 * 
	 * @param b
	 *         the byte
	 * @return the positive value
	 */
	public static int positive(byte b) {
		int num = b;
		return num & 0xff;
	}
	
	public static void main(String[] args) {
		int b = (int) 0x81; // 1000 0001
		System.out.printf("%d, %d, %d\n", bitget(b, 0), bitget(b, 1), bitget(b, 7)); // 1, 0, 1
		System.out.printf("%x\n", positive((byte) bitset(b, 6, 1))); // 83
		System.out.printf("%x\n", positive((byte) bitset(b, 0, 0))); // 1
		System.out.printf("%x\n", positive((byte) b)); 
	}
}
